package com.qianchang.microfinance.view.login;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.qianchang.microfinance.R;
import com.qianchang.microfinance.global.ConstantAppInfo;
import com.qianchang.microfinance.setting.SettingTradPasswordActivity;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.DMLog;
import com.dm.library.utils.FormatUtil;
import com.dm.library.utils.MD5Util;
import com.dm.library.utils.StringUtils;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.element.DTextView;
import com.qianchang.microfinance.view.dialog.alert.DimengSingleButtonAlertDialog;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.qianchang.microfinance.global.ConstantAppInfo.DEFAULT_TIME;


/**
 * 版 权: 深圳市迪蒙网络科技有限公司
 * 描 述: <忘记密码第二步>
 * 修 改 人: fengye
 * 修改时间: 2017-1-16
 */

public class ForgetActivityTwo extends BaseActivity implements TextWatcher {
    private static final String TAG = "ForgetActivityTwo";
    @BindView(R.id.et_input_checkcode)
    EditText etInputCheckcode;
    @BindView(R.id.iv_checkcode)
    DTextView ivCheckcode;
    @BindView(R.id.ll_checkcode)
    LinearLayout llCheckcode;
    @BindView(R.id.et_input_pwd)
    EditText etInputPwd;
    @BindView(R.id.iv_pwd_visible)
    CheckBox ivPwdVisible;
    @BindView(R.id.btn_forget_pwd_one_next)
    Button btnForgetPwdOneNext;


    /**
     * 手机验证码倒计时
     */
    private CountDownTimer phoneDownTimer;
    private String phone = "";
    private boolean isTradPwd;//修改登录  还是  支付密码

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_pwd_two);
        ButterKnife.bind(this);
        initView();
        initData();
    }

    @Override
    protected void initView() {
        super.initView();
        Intent intent = getIntent();
        ivPwdVisible.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int length = etInputPwd.getText().length();
                if (isChecked) {
                    etInputPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    etInputPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                etInputPwd.setSelection(length);
            }
        });
        if (intent.hasExtra(SettingTradPasswordActivity.IS_TRAD_PWD) && intent.getBooleanExtra(SettingTradPasswordActivity.IS_TRAD_PWD, false)) {
            isTradPwd = true;
            setTitleName(getString(R.string.titleFindTranPassword));
            etInputPwd.setInputType(InputType.TYPE_NUMBER_VARIATION_PASSWORD | InputType.TYPE_CLASS_NUMBER);
            etInputPwd.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
            etInputPwd.setHint(getString(R.string.hint_input_new_trad_pwd));
//            setTitle(getString(R.string.titleFindTranPassword));
        } else {
            setTitleName(getString(R.string.titleFindLoginPassword));
            etInputPwd.setHint(getString(R.string.hint_input_new_login_pwd));
        }

        etInputCheckcode.addTextChangedListener(this);
        etInputPwd.addTextChangedListener(this);
    }

    @Override
    protected void initData() {
        super.initData();
        phone = getIntent().getStringExtra("phone");
        sendCaptcha(phone);
    }


    //显示获取手机验证码倒计时
    private void showRemainTime() {
        ivCheckcode.setEnabled(true);
        phoneDownTimer = new CountDownTimer(DEFAULT_TIME, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                int temp = (int) (millisUntilFinished / 1000);
                ivCheckcode.setText(temp + "S");
                ivCheckcode.setEnabled(false);
            }

            @Override
            public void onFinish() {
                ivCheckcode.setText(getString(R.string.btn_get_verify_code));
                ivCheckcode.setEnabled(true);
            }
        }.start();
    }

    /**
     * 获取手机验证码
     */
    private void getPhoneCode() {
        //获取验证码
        if (StringUtils.isEmpty(phone)) {
            ToastUtil.getInstant().show(this, getString(R.string.msg_input_correct_account));
            return;
        }
        sendCaptcha(phone);
    }

    /**
     * 发送验证码
     */
    private void sendCaptcha(String s_phone) {
        HttpParams params = new HttpParams();
        params.put("verifyType", "0");//0 短信；1 邮箱；2：语音
        params.put("phone", s_phone);
        params.put("msgType", "0");//【忘记密码：0、注册:1】
        if (isTradPwd) {//是支付密码
            params.put("busType", "3");
        } else {
            params.put("busType", "2"); // 1：注册  2：找回登录密码 3：找回支付密码 4： 修改登录密码 5：绑定银行卡 6：绑定手机 7：修改手机号码 8 免密登录
        }

        DMOKHttpUtils.getInstance().post(getApplicationContext(), DMConstant.ApiURL.SEND_IDENTIFY_CODE, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(JsonResult<String> response) {
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    ToastUtil.getInstant().show(ForgetActivityTwo.this, getString(R.string.msg_indentity_code_send_success));
                    showRemainTime();
                } else {
                    ToastUtil.getInstant().show(ForgetActivityTwo.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                ToastUtil.getInstant().show(ForgetActivityTwo.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
            }

        });
    }

    @OnClick({R.id.iv_checkcode, R.id.btn_forget_pwd_one_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_checkcode:
                getPhoneCode();
                break;
            case R.id.btn_forget_pwd_one_next:
                if (isTradPwd) {//支付密码
                    changeTranPwd();
                } else {//登录密码
                    changeLoginPwd();
                }
                break;
        }
    }

    private void changeTranPwd() {
        /**
         * 修改支付密码
         */
        String identifyCode = etInputCheckcode.getText().toString().trim();
        String pwd = etInputPwd.getText().toString().trim();

        if (StringUtils.isEmpty(identifyCode)) {
            ToastUtil.getInstant().show(ForgetActivityTwo.this, getString(R.string.msg_identify_code_not_null));
            return;
        }

        if (!FormatUtil.isValidTradPwd(pwd)) {
            ToastUtil.getInstant().show(ForgetActivityTwo.this, getString(R.string.msg_trad_pwd_isnot_ok));
            return;
        }

        show();
        HttpParams params = new HttpParams();
        params.put("veryCode", identifyCode);
        params.put("newTransactionPwd", MD5Util.string2MD5(
                pwd + ConstantAppInfo.Password.PASSWORD_SUFFIX));
        params.put("type", "2");        /**1表示修改,2表示找回*/
        params.put("phone", phone);

        DMOKHttpUtils.getInstance().post(getApplicationContext(), DMConstant.ApiURL.UPDATE_FORGET_TRAN_PWD, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(JsonResult<String> response) {
                dismiss();
                DMLog.i(TAG, response.toString());
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    ForgetActivityTwo.this.finish();
                } else {
                    ToastUtil.getInstant().show(ForgetActivityTwo.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(ForgetActivityTwo.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
                dismiss();
            }

        });
    }

    /**
     * 修改密码
     */
    private void changeLoginPwd() {
        String identifyCode = etInputCheckcode.getText().toString().trim();
        String pwd = etInputPwd.getText().toString().trim();
        if (StringUtils.isEmpty(identifyCode)) {
            ToastUtil.getInstant().show(ForgetActivityTwo.this, getString(R.string.msg_identify_code_not_null));
            return;
        }

        if (!FormatUtil.isValidPassword(pwd, null)) {
            ToastUtil.getInstant().show(ForgetActivityTwo.this, getString(R.string.msg_pwd_length_too_short));
            return;
        }

        show();
        HttpParams params = new HttpParams();
        params.put("veryCode", identifyCode);//0 短信；1 邮箱；2：语音
        params.put("phone", phone);
        params.put("newPassword", MD5Util.string2MD5(pwd + ConstantAppInfo.Password.PASSWORD_SUFFIX));
//        params.put("type", "0");//

        DMOKHttpUtils.getInstance().post(getApplicationContext(), DMConstant.ApiURL.UPDATE_PWD_BY_PHONE, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(JsonResult<String> response) {
                dismiss();
                Log.i(TAG, response.toString());
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    showReLoginDialog();
                } else {
                    ToastUtil.getInstant().show(ForgetActivityTwo.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(ForgetActivityTwo.this, msg);// getString(R.string.msg_indentity_code_send_fail));
            }

            @Override
            public void onConnectFailure(String msg) {
                ToastUtil.getInstant().show(ForgetActivityTwo.this, msg);
            }

        });
    }

    private void showReLoginDialog() {
        DimengSingleButtonAlertDialog singleButtonAlertDialog = DimengSingleButtonAlertDialog.newInstance("", "密码修改成功，请重新登录！");
        singleButtonAlertDialog.setOnDialogClickListener(new DimengSingleButtonAlertDialog.OnDialogClickListener() {
            @Override
            public void agree() {
                startActivity(LoginActivity.class);
            }
        });
        singleButtonAlertDialog.show(getSupportFragmentManager(), getClass().getSimpleName());

    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    /**
     * 文本变化之后检测
     *
     * @param s
     */
    @Override
    public void afterTextChanged(Editable s) {
        checkButtonEnable();
    }

    /**
     * 检测按钮是否激活
     */
    private void checkButtonEnable() {
        String s_1 = etInputCheckcode.getText().toString();
        String s_2 = etInputPwd.getText().toString();

        if (isTradPwd) {//支付密码
            if (!StringUtils.isEmptyOrNull(s_1) && FormatUtil.isVerificatCode(s_2)) {
                btnForgetPwdOneNext.setEnabled(true);
            } else {
                btnForgetPwdOneNext.setEnabled(false);
            }
        } else {
            if (!StringUtils.isEmptyOrNull(s_1) && FormatUtil.isValidPassword(s_2)) {
                btnForgetPwdOneNext.setEnabled(true);
            } else {
                btnForgetPwdOneNext.setEnabled(false);
            }
        }


    }
}
